﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ProtectedAPI.Controllers
{

    public class APIBaseController : ControllerBase, IActionFilter
    {

        public int CurrentTenantId { get; set; }
        public List<string> CurrentRoleId { get; set; }

        [NonAction]
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
        [NonAction]
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var allowAnonymous = action.MethodInfo.GetCustomAttributes(typeof(Microsoft.AspNetCore.Authorization.IAllowAnonymous), false).FirstOrDefault();

            if (allowAnonymous == null)
            {
                var headers = HttpContext.Request.Headers;

                if (!headers.ContainsKey("Authorization"))
                {
                    context.Result = Unauthorized(new { succ = false, msg = "未授权" });// NotFound(new { succ = false, msg = "您的请求未找到：404！" });
                    return;
                }
                var bearToken = headers["Authorization"].FirstOrDefault().Trim();
                if (string.IsNullOrWhiteSpace(bearToken))
                {
                    context.Result = Unauthorized(new { succ = false, msg = "未授权" });// NotFound(new { succ = false, msg = bearToken });
                    return;
                }
                bearToken = bearToken.Replace("Bearer ", "")
                    .Replace("Bearer", "").Replace("bearer ", "").Replace("bearer", "");
                var jwtHander = new JwtSecurityTokenHandler();
                try
                {
                    JwtSecurityToken jwtSecurityToken = jwtHander.ReadJwtToken(bearToken);

                    var exp = jwtSecurityToken.Claims.Where(c => c.Type == "exp").FirstOrDefault().Value;
                    DateTime startUnixTime = System.TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local);
                    var dueTime = startUnixTime.AddSeconds(double.Parse(exp));//token过期时间
                    if ((DateTime.Now - dueTime).TotalMinutes < 1)//即将过期
                    {
                        //用户标识
                        //  jwtSecurityToken.ti
                        //var newToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
                        //    jwtSecurityToken.Issuer,
                        //    jwtSecurityToken.Audiences.FirstOrDefault(),
                        //    jwtSecurityToken.Claims, expires: DateTime.Now.AddMinutes(30),
                        //    signingCredentials: jwtSecurityToken.SigningCredentials)
                        //    );
                    }

                    int id = -1;
                    var isInt = int.TryParse(jwtSecurityToken.Claims.Where(c => c.Type == "Tenant_Id").FirstOrDefault().Value, out id);
                    if (isInt)
                    {
                        CurrentTenantId = id;
                    }
                    else
                    {
                        context.Result = NotFound(new { succ = false, msg = bearToken });
                        return;
                    }
                    CurrentRoleId = jwtSecurityToken.Claims.Where(c => c.Type == "RoleId").FirstOrDefault().Value.Split(",").ToList();
                }
                catch (Exception e)
                {
                    context.Result = Unauthorized(new { succ = false, msg = e.Message });
                }
            }


        }
    }
}